package com.example.teesystem.common.Permission;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.teesystem.common.cache.CourseCache;
import com.example.teesystem.common.cache.IssueCache;
import com.example.teesystem.common.cache.UserCache;
import com.example.teesystem.common.exception.CustomException;
import com.example.teesystem.common.utils.PermissionUtil;
import com.example.teesystem.common.utils.ResultCode;
import com.example.teesystem.filter.MyHandlerInterceptor;
import com.example.teesystem.mapper.AssistantMapper;
import com.example.teesystem.mapper.ExamPaperMapper;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Map;


/**
 * @author pxr
 * @data 2022/5/11 18:24
 */
@Aspect
@Component
@RequiredArgsConstructor
@Order(1)
public class PermissionAspect {

    private final AssistantMapper assistantMapper;
    private final ExamPaperMapper examPaperMapper;
    private final HttpServletRequest request;

    @Pointcut("@annotation(com.example.teesystem.common.Permission.PermissionCheck)")
    public void PermissionChecked() {
    }

    @Before("PermissionChecked()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        //转换成子类 获取目标方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取接口方法
        Method method = signature.getMethod();
        Method implMethod = joinPoint.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
        //获取方法上的注解
        PermissionCheck permissionCheck = implMethod.getAnnotation(PermissionCheck.class);
        Map<String,String[]> map = request.getParameterMap();
        System.out.println(map);
        if(permissionCheck != null){//有权限
            if(UserCache.userMap.get(MyHandlerInterceptor.getUid()).getType() != 0){//非管理员
                JSON json = JSONUtil.parse(joinPoint.getArgs()[0]);
                System.out.println(json);
                String issue_id,paper_id,Id,course_id = null;
                Integer courseId, issueId,paperId,id;
                ArrayList<String> arrayList = null;
                try{
                    System.out.println("arraylist");
                    arrayList = (ArrayList)json.getByPath("courseId");
                    if(arrayList!=null){
                        for (String s : arrayList) {
                            course_id = s;
                        }
                    }
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    course_id = String.valueOf(json.getByPath("courseId"));
                }
                try{
                    assert course_id != null;
                    courseId = Integer.parseInt(course_id);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    courseId = null;
                }
                try{
                    issue_id = String.valueOf(json.getByPath("issueId"));
                    issueId = Integer.parseInt(issue_id);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    issueId = null;
                }
                try{
                    Id = String.valueOf(json.getByPath("id"));
                    id = Integer.parseInt(Id);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    id = null;
                }
                try{
                    paper_id = String.valueOf(json.getByPath("paperId"));
                    paperId = Integer.parseInt(paper_id);
                    System.out.println(paperId);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    paperId = null;
                }

                if(map.containsKey("courseId")){
                    courseId = Integer.parseInt(map.get("courseId")[0]);
                    System.out.println("map:"+courseId);
                }

                if(courseId==null){
                    if(paperId != null){
                        courseId = examPaperMapper.getCourseIdByPaperId(paperId);
                    }
                    else if(issueId != null){
                        courseId = IssueCache.issueMap.get(issueId);
                    }else if(id != null){
                        courseId = id;
                    }
                }

                if(courseId == null){
                    throw new CustomException(ResultCode.NO_PERMISSION);
                }
                else {
                    if(CourseCache.courseMap.get(courseId)!=null){
                        if(CourseCache.courseMap.get(courseId).getTeacher()==MyHandlerInterceptor.getUid()){
                            return;
                        }
                    }
                    long permission = permissionCheck.value();
                    Long myPer = assistantMapper.getAssistantPermission(MyHandlerInterceptor.getUid(),courseId);
                    if(myPer == null){
                        throw new CustomException(ResultCode.ASSISTANT_PERMISSION_ERROR);
                    }else {
                        if(!PermissionUtil.verify(myPer,permission)) {
                            throw new CustomException(ResultCode.ASSISTANT_PERMISSION_ERROR);
                        }
                    }
                }

            }
        }

    }

}
